package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.SimpleDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DynamicConfigLab;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.CustomerRelationKeyDepartment.DepartMentList;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 添加新部门
 *
 * @author yhh
 */
public class CustomerRelationAddDepartmentFragment extends BaseFragment {
  protected static final String TAG = CustomerRelationAddDepartmentFragment.class.getName();
  protected static final String EXTRA_DEPARTMENT = "com.isunland.managesystem.ui.extra_department";
  //protected static final int REQUEST_CLEAR_SUPERDEPARTMENT = 3;
  protected static final int REQUEST_CLEAR_DIRCT_MANAGER = 4;
  protected static final int REQUEST_CLEAR__MANAGER = 5;
  //private static final int REQUEST_CHOOSE_SUPERDEPARTMENT = 0;
  private static final int REQUEST_MANAGER = 1;
  private static final int REQUEST_DIRCT_MANAGER = 2;
  private static final int SAVE = 6;
  private static final int SAVE_CHECK = 7;
  private EditText etDepartmentName; // 部门名称
  // private TextView tvCerateDepartmentTime; //部门创建时间
  private TextView mEtDepartmentManager;// 部门经理
  private TextView mEtDirectorDepartmentManager;// 部门主管领导
  private EditText tvDutyConstruction;// 部门职责
  //private TextView etSuperDeaprtment;// 上级部门
  //private BaseVolleyActivity mActivity;
  //private String customerName;// 客户名
  private CurrentUser mCurrentUser;

  //private String superDepartMentName;
  //private String superDepartmentId;// 上级部门id.
  private String departmentId;// 新增部门id.
  private String mUuid;
  private String mCustomerId;
  //private Callbacks mCallbacks;

  public static Fragment newInstance(DepartMentList department) {

    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_DEPARTMENT, department);
    CustomerRelationAddDepartmentFragment fragment = new CustomerRelationAddDepartmentFragment();
    fragment.setArguments(bundle);
    return fragment;
  }

  //@SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) {
  //  super.onAttach(activity);
  //  mCallbacks = (Callbacks) activity;
  //}

  //@Override public void onDetach() {
  //  super.onDetach();
  //  mCallbacks = null;
  //}

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    setTitleCustom(MyStringUtil.connect(R.string.add, R.string.customerKeyDepartment1));
    mCurrentUser = CurrentUser.newInstance(getActivity());
    mCustomerId =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.CUSTOMER_ID, "");
    mUuid = String.valueOf(System.currentTimeMillis() / 1000);
    departmentId = UUID.randomUUID().toString();
  }

  /**
   * 添加提交按钮
   */
  @SuppressWarnings("JavaDoc") @Override public void onCreateOptionsMenu(Menu menu,
      MenuInflater inflater) {
    inflater.inflate(R.menu.menu_save_submit, menu);
    menu.getItem(1).setTitle(R.string.saveAndSubmit);
    super.onCreateOptionsMenu(menu, inflater);
  }

  /**
   * 加载页面
   */
  @SuppressWarnings("JavaDoc") @Override public View onCreateView(LayoutInflater inflater,
      ViewGroup container, Bundle savedInstanceState) {
    View view =
        inflater.inflate(R.layout.fragment_add_department_customerrelation, container, false);
    etDepartmentName = (EditText) view.findViewById(R.id.et_departmentName_customerRelation);
    mEtDepartmentManager = (TextView) view.findViewById(R.id.et_departmentManager_customerRelation);
    ImageView mivManagerAddDepartment =
        (ImageView) view.findViewById(R.id.iv_manager_addDepartment);
    //TextView tvDataCondition = (TextView) view.findViewById(R.id.tv_dataCondition_customerRelation);
    TextView etRegister = (TextView) view.findViewById(R.id.et_register_customerRelation);
    tvDutyConstruction = (EditText) view.findViewById(R.id.tv_dutyConstruction_customerRelation);
    //etSuperDeaprtment = (TextView) view.findViewById(R.id.et_superDeaprtment_customerRelation);
    mEtDirectorDepartmentManager =
        (TextView) view.findViewById(R.id.et_directorDepartmentManager_customerRelation);
    ImageView mivDirectorAddDepartment =
        (ImageView) view.findViewById(R.id.iv_director_addDepartment);

    //etSuperDeaprtment.setOnClickListener(new OnClickListener() {
    //
    //  @Override public void onClick(View v) {
    //    if (TextUtils.isEmpty(etSuperDeaprtment.getText().toString().trim())) {
    //
    //      showDialog(REQUEST_CHOOSE_SUPERDEPARTMENT);
    //    } else {
    //      showDialog(REQUEST_CLEAR_SUPERDEPARTMENT);
    //    }
    //  }
    //});

    mivManagerAddDepartment.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        if (TextUtils.isEmpty(mEtDepartmentManager.getText().toString().trim())) {

          showDialog(REQUEST_MANAGER);
        } else {
          showDialog(REQUEST_CLEAR__MANAGER);
        }
      }
    });

    mivDirectorAddDepartment.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {

        if (TextUtils.isEmpty(mEtDirectorDepartmentManager.getText().toString().trim())) {

          showDialog(REQUEST_DIRCT_MANAGER);
        } else {
          showDialog(REQUEST_CLEAR_DIRCT_MANAGER);
        }
      }
    });

    String uerName = mCurrentUser.getRealName();

    etRegister.setText(uerName);
    DynamicConfigLab dynamicConfig =
        DynamicConfigLab.newInstance(mActivity, getString(R.string.module_deptColumns));
    dynamicConfig.autoConfigTitle(view);
    dynamicConfig.autoConfigVisiblity(view);
    return view;
  }

  /**
   * 对返回按钮和提交按钮事件进行处理
   */
  @SuppressWarnings("JavaDoc") @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;

      case R.id.menu_item_save:
        String department = etDepartmentName.getText().toString().trim();
        if (TextUtils.isEmpty(department)) {
          Toast.makeText(getActivity(), R.string.completeDepartment, Toast.LENGTH_SHORT).show();
        } else {
          volleyPostSave(SAVE);
        }
        break;
      //保存并审核
      case R.id.menu_item_submit:
        if (TextUtils.isEmpty(etDepartmentName.getText().toString().trim())) {
          Toast.makeText(getActivity(), R.string.completeDepartment, Toast.LENGTH_SHORT).show();
        } else {
          showDialog(SAVE_CHECK);
        }
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void volleyPostSave(final int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DEPARTMENT_SAVE);
    HashMap<String, String> params = new HashMap<>();

    String orgName = etDepartmentName.getText().toString(); // 部门名称
    String dutyDescript = tvDutyConstruction.getText().toString();// 部门职责说明
    String customerName =
        SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.CUSTOMER_NAME,
            "");// 客户名称
    String managerName = mEtDepartmentManager.getText().toString(); // 部门经理名称
    String directorName = mEtDirectorDepartmentManager.getText().toString();// 主管部门领导

    params.put("id", departmentId);//部门id

    params.put("orgId", mUuid);
    params.put("orgName", orgName);

    //if (!TextUtils.isEmpty(superDepartMentName)) {
    //  params.put("pid", superDepartmentId);
    //} else {
    //  params.put("pid", mCustomerId);
    //}

    if (!TextUtils.isEmpty(dutyDescript)) {
      params.put("dutyDescript", dutyDescript);
    } else {
      params.put("dutyDescript", "");
    }

    if (!TextUtils.isEmpty(customerName)) {
      params.put("customerName", customerName);
    } else {
      params.put("customerName", "");
    }

    if (!TextUtils.isEmpty(mCustomerId)) {
      params.put("customerId", mCustomerId);
    } else {
      params.put("customerId", "");
    }

    if (!TextUtils.isEmpty(managerName)) {
      params.put("managerName", managerName);
    } else {
      params.put("managerName", "");
    }

    if (!TextUtils.isEmpty(directorName)) {
      params.put("directorName", directorName);
    } else {
      params.put("directorName", "");
    }
    Log.i(TAG, "params==============" + params.toString());
    MyUtils.showDialogLoading(mActivity);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage workProcess;
        try {
          MyUtils.dismissDialog();
          Log.i(TAG, "response=" + arg0);
          workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == workProcess || null == workProcess.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = workProcess.getResult();
          if (successType.equals(SuccessMessage.SUCCESS)) {
            if (SAVE == requestCode) {
              Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
              getActivity().setResult(Activity.RESULT_OK);
              //mCallbacks.onRefresh(mCustomerId, departmentId);
              mActivity.finish();
            } else if (SAVE_CHECK == requestCode) {
              volleyPostSubmit(SAVE_CHECK);
            }
          } else if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  // 提交审核部门
  private void volleyPostSubmit(final int requestCode) {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DEARTMENT_CHECK);
    HashMap<String, String> depatementSub = new HashMap<>();

    depatementSub.put("ids", "'" + departmentId + "'");
    depatementSub.put("newDataStatus", "publish");
    mActivity.volleyPost(url, depatementSub, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            if (SAVE == requestCode) {
              Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            } else if (SAVE_CHECK == requestCode) {
              Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            }
            getActivity().setResult(Activity.RESULT_OK);
            mActivity.finish();
            //mCallbacks.onRefresh(mCustomerId, mUuid);
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  private void showDialog(int requestCode) {
    DialogFragment dialog = null;
    switch (requestCode) {
      //case REQUEST_CHOOSE_SUPERDEPARTMENT:
      //  dialog = new CustomerRelationSuperDepartmentDialogFragment();
      //  break;

      case REQUEST_MANAGER:
        dialog = new CustomerMemberDialogFragment();
        break;
      case REQUEST_DIRCT_MANAGER:
        dialog = new CustomerMemberDialogFragment();
        break;
      case REQUEST_CLEAR__MANAGER:
        dialog = SimpleDialogFragment.newInstance(R.string.chooseOperation, R.string.edit, 0,
            R.string.clearChoose);
        break;
      case REQUEST_CLEAR_DIRCT_MANAGER:
        dialog = SimpleDialogFragment.newInstance(R.string.chooseOperation, R.string.edit, 0,
            R.string.clearChoose);
        break;
      //case REQUEST_CLEAR_SUPERDEPARTMENT:
      //  dialog = SimpleDialogFragment.newInstance(R.string.chooseOperation, R.string.edit, 0,
      //      R.string.clearChoose);
      //  break;
      case SAVE_CHECK:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.submitConfirm);
      default:
        break;
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    if (dialog != null) {
      dialog.setTargetFragment(CustomerRelationAddDepartmentFragment.this, requestCode);
      dialog.show(fm, "");
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;

    switch (requestCode) {
      case REQUEST_MANAGER:
        CustomerDialog result =
            (CustomerDialog) data.getSerializableExtra(CustomerMemberDialogFragment.EXTRA_VALUE);
        mEtDepartmentManager.setText(result.getName());
        //String mManagerId = result.getId();
        break;
      case REQUEST_CLEAR__MANAGER:
        int choice = data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE,
            SimpleDialogFragment.VALUE_POSITIVE);
        if (choice == SimpleDialogFragment.VALUE_POSITIVE) {
          showDialog(REQUEST_MANAGER);
        } else {
          mEtDepartmentManager.setText("");
        }
        break;
      case REQUEST_DIRCT_MANAGER:
        CustomerDialog result1 =
            (CustomerDialog) data.getSerializableExtra(CustomerMemberDialogFragment.EXTRA_VALUE);
        mEtDirectorDepartmentManager.setText(result1.getName());
        //String mDirictManagerId = result1.getId();
        break;
      case REQUEST_CLEAR_DIRCT_MANAGER:
        int choice2 = data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE,
            SimpleDialogFragment.VALUE_POSITIVE);
        if (choice2 == SimpleDialogFragment.VALUE_POSITIVE) {
          showDialog(REQUEST_DIRCT_MANAGER);
        } else {
          mEtDirectorDepartmentManager.setText("");
        }
        break;
      //case REQUEST_CHOOSE_SUPERDEPARTMENT:

      //CustomerDialog department = (CustomerDialog) data.getSerializableExtra(
      //    CustomerRelationSuperDepartmentDialogFragment.EXTRA_VALUE);
      //superDepartMentName = department.getName();
      // superDepartMentName=CustomerRelationDepartmentDetail.getDirectDepartment(superDepartMentName);
      //superDepartmentId = department.getId();

      //etSuperDeaprtment.setText(superDepartMentName);
      //break;

      //case REQUEST_CLEAR_SUPERDEPARTMENT:
      //  int choice3 = data.getIntExtra(SimpleDialogFragment.EXTRA_CHOICE,
      //      SimpleDialogFragment.VALUE_POSITIVE);
      //  if (choice3 == SimpleDialogFragment.VALUE_POSITIVE) {
      //    showDialog(REQUEST_CHOOSE_SUPERDEPARTMENT);
      //  } else {
      //    etSuperDeaprtment.setText("");
      //    superDepartmentId = "";
      //  }
      //  break;
      case SAVE_CHECK:
        volleyPostSave(SAVE_CHECK);
        break;
      default:
        break;
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  public interface Callbacks {
    void onRefresh(String customerId, String uuid);
  }
}